<template>
	<view class="login-container">
		<!-- 主登录页面背景 -->
		<image class="login-bg" src="/static/登录.jpg"></image>

		<!-- 四个透明按钮覆盖层 -->
		<view class="button-overlays">
			<!-- WhatsApp 登录按钮 -->
			<view class="overlay-btn whatsapp-btn" @click="onWhatsAppLogin"></view>

			<!-- Facebook 登录按钮 -->
			<view class="overlay-btn facebook-btn" @click="onFacebookLogin"></view>

			<!-- 密码登录按钮 -->
			<view class="overlay-btn password-btn" @click="onPasswordLogin"></view>

			<!-- 验证码登录按钮 -->
			<view class="overlay-btn sms-btn" @click="onSmsLogin"></view>
		</view>

		<!-- 遮罩层 -->
		<view v-if="showModal" class="modal-mask" @click="onClose">
			<!-- 登录弹框：内部通过 currentTab 切换 账密/验证码 登录，不再同时展示两套 -->
			<view class="login-modal" @click.stop>
				<view class="modal-header">
					<image class="modal-title" type="image"
						:src="currentTab === 'password' ? '/static/忘记密码标题.png' : '/static/验证码登录.png'" alt=""
						mode="widthFix" />
					<image class="modal-close" type="image" src="/static/close.png" alt="" @click="onClose" />
				</view>

				<view class="modal-content">
					<!-- 输入区域：账密登录 -->
					<view v-if="currentTab === 'password'">
						<view class="input-group" style="margin-bottom: 100rpx">
							<view class="img-box">
								<image mode="widthFix" class="label-img" src="/static/手机号.png" alt="" />
							</view>
							<view class="input-wrapper">
								<input class="input-field" placeholder="" v-model="mobile " />
							</view>
						</view>

						<view class="input-group">
							<view class="img-box">
								<image mode="widthFix" class="label-img" src="/static/密码1.png" alt=""
									style="width: 240rpx;" />
							</view>
							<view class="input-wrapper">
								<input class="input-field" type="password" placeholder="" v-model="password" />
							</view>
						</view>

						<view class="forgot-password">
							<text class="forgot-link" @click="onForgot">Esqueceu a senha</text>
						</view>

						<view class="button-group">
							<image mode="widthFix" src="/static/注册.png" alt="" @click="onRegister" />
							<image mode="widthFix" src="/static/登录按钮.png" alt="" @click="onSubmitPassword" />
						</view>
					</view>

					<!-- 输入区域：验证码登录 -->
					<view v-else>
						<view class="input-group" style="margin-bottom: 100rpx">
							<view class="img-box">
								<image mode="widthFix" class="label-img" src="/static/手机号.png" alt="" />
							</view>
							<view class="input-wrapper">
								<input class="input-field" placeholder="" v-model="mobile " />
							</view>
						</view>

						<view class="input-group">
							<view class="img-box">
								<image mode="widthFix" class="label-img" src="/static/验证码1.png" alt=""
									style="width: 420rpx;" />
							</view>
							<view class="input-wrapper">
								<input class="input-field" placeholder="" v-model="smsCode" />
								<image class="sendMsg" :class="{ disabled: isCounting || sendingCode }"
									:src="'/static/发送验证码.png'" @click="onSendCode" />
								<view v-if="isCounting" class="countdown-mask">{{ countdown }}s</view>
							</view>
						</view>

						<view class="button-group">
							<image mode="widthFix" src="/static/登录按钮.png" alt="" @click="onSubmitSms" />
						</view>
					</view>

				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue'
	import {
		loginWithPassword,
		loginWithSms,
		sendVerificationCode,
	} from '@/api/login.js'

	import {
		onLoad
	} from '@dcloudio/uni-app'

	import {
		handleLoginSuccess,
		getUrlParams
	} from "../../utils/utils.js"

	const showModal = ref(false) // 控制弹框显隐
	const currentTab = ref('password') // 'password' | 'sms'
	const mobile = ref('')
	const password = ref('')
	const smsCode = ref('')

	const loading = ref(false)
	const sendingCode = ref(false)
	const countdown = ref(60)
	const isCounting = ref(false)
	let timer = null

	function validatePhone(phone) {
		return /^\d{6,15}$/.test(String(phone).trim())
	}

	function toast(title = '操作成功') {
		uni.showToast({
			title,
			icon: 'none'
		})
	}
	

	let urlParams
	onLoad(() => {
		urlParams = getUrlParams();
	})

	function onShowModal() {
		showModal.value = true
	}

	function onClose() {
		showModal.value = false
		// 清理倒计时
		if (timer) {
			clearInterval(timer)
			timer = null
			isCounting.value = false
			countdown.value = 60
		}
	}

	async function onSubmitPassword() {
		if (!validatePhone(mobile.value) || !password.value) {
			return toast('请输入正确的手机号和密码')
		}
		if (loading.value) return
		loading.value = true
		try {
			const res = await loginWithPassword(mobile.value, password.value)
			toast('登录成功')
			onClose() // 关闭弹框
			handleLoginSuccess(res.data.token, urlParams.invite_code)
		} catch (e) {
			toast(e.message || '登录失败')
		} finally {
			loading.value = false
		}
	}

	async function onSubmitSms() {
		if (!validatePhone(mobile.value) || !smsCode.value) {
			return toast('请输入正确的手机号与验证码')
		}
		if (loading.value) return
		loading.value = true
		try {
			const res = await loginWithSms(mobile.value, smsCode.value)
			toast('登录成功')
			onClose() // 关闭弹框
			//根据内核执行不同的登录回调
			handleLoginSuccess(res.data.token)
		} catch (e) {
			toast(e.message || '登录失败')
		} finally {
			loading.value = false
		}
	}

	function startCountdown() {
		isCounting.value = true
		countdown.value = 60
		timer && clearInterval(timer)
		timer = setInterval(() => {
			if (countdown.value <= 1) {
				clearInterval(timer)
				isCounting.value = false
				countdown.value = 60
				return
			}
			countdown.value--
		}, 1000)
	}

	async function onSendCode() {
		if (isCounting.value || sendingCode.value) return
		if (!validatePhone(mobile.value)) {
			return toast('请输入正确的手机号')
		}
		sendingCode.value = true
		try {
			await sendVerificationCode(mobile.value, 'login')
			toast('验证码已发送')
			startCountdown()
		} catch (e) {
			toast(e.message || '验证码发送失败')
		} finally {
			sendingCode.value = false
		}
	}

	function onForgot() {
		// 可跳转到忘记密码页或弹出 uni-popup
		toast('忘记密码 - 待接入')
	}

	function onRegister() {
		// 可跳转到注册页或弹出 uni-popup
		toast('注册 - 待接入')
	}

	// 四个透明按钮点击事件
	function onWhatsAppLogin() {
		// toast('WhatsApp登录启动中...')
		// 模拟WhatsApp登录逻辑
		setTimeout(() => {
			const mockLoginSuccess = Math.random() > 0.3
			if (mockLoginSuccess) {
				const mockToken = 'whatsapp_token_' + Date.now()
				// toast('WhatsApp登录成功')
				// 调用登录成功处理
				handleLoginSuccess(mockToken)
			} else {
				toast('WhatsApp登录失败，请重试')
			}
		}, 2000)
	}

	function onFacebookLogin() {
		// toast('Facebook登录启动中...')
		// 模拟Facebook登录逻辑
		setTimeout(() => {
			const mockLoginSuccess = Math.random() > 0.3
			if (mockLoginSuccess) {
				const mockToken = 'facebook_token_' + Date.now()
				// toast('Facebook登录成功')
				// 调用登录成功处理
				handleLoginSuccess(mockToken)
			} else {
				toast('Facebook登录失败，请重试')
			}
		}, 2000)
	}

	function onPasswordLogin() {
		// 切换到密码登录模式并显示弹框
		currentTab.value = 'password'
		showModal.value = true
	}

	function onSmsLogin() {
		// 切换到验证码登录模式并显示弹框
		currentTab.value = 'sms'
		showModal.value = true
	}
</script>

<style lang="scss" scoped>
	.login-container {
		position: relative;
		min-height: 100vh;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		.login-bg {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			z-index: 1;
			cursor: pointer;
		}

		/* 透明按钮覆盖层：根据视觉设计在底部四个按钮区域放置点击层 */
		.button-overlays {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			z-index: 2;
			/* 高于背景图 */
			pointer-events: none;
			/* 默认不拦截，只有按钮区域开启 */
			cursor: pointer;
		}

		.overlay-btn {
			position: absolute;
			bottom: 18%;
			/* 底部距离可按需调整 */
			height: 12%;
			/* 高度根据按钮视觉高度调整 */
			border-radius: 999px;
			/* 点击区域开启事件 */
			pointer-events: auto;
			/* 完全透明但可点击 */
			background: rgba(255, 255, 255, 0.01);
		}

		/* 四个按钮的水平位置：按 4 等分布局并留间距，可微调 */
		.whatsapp-btn {
			left: 8%;
			width: 20%;
		}

		.facebook-btn {
			left: 28%;
			width: 20%;
		}

		.password-btn {
			left: 52%;
			width: 20%;
		}

		.sms-btn {
			left: 73%;
			width: 20%;
		}

		.modal-mask {
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background-color: rgba(0, 0, 0, 0.5);
			z-index: 999;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.login-modal {
			position: relative;
			width: 1600rpx;
			min-height: 1000rpx;
			border-radius: 15px;
			overflow: hidden;
			background: url("/static/小弹框bg.png") no-repeat;
			background-size: 100% 100%;
			animation: modalSlideIn 0.3s ease-out;

			.modal-header {
				padding: 15px 20px;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.modal-title {
					padding-top: 60rpx;
					width: 800rpx;
					margin: 0 auto;
				}

				.modal-close {
					width: 90rpx;
					height: 90rpx;
					padding: 20rpx;
					cursor: pointer;
					transition: opacity 0.2s;

					&:hover {
						opacity: 0.7;
					}
				}
			}

			.modal-content {
				padding: 100rpx 160rpx;

				.input-group {
					display: flex;
					align-items: center;
					align-items: flex-end;

					.img-box {
						width: 40%;
						display: flex;
						justify-content: flex-end;
						margin-right: 20rpx;
					}

					.input-wrapper {
						background: #f2d9bb;
						border-radius: 26rpx 0 26rpx 0;
						width: 1000rpx;
						height: 70rpx;
						flex: 1;
						padding: 20rpx 30rpx;
						position: relative;

						.sendMsg {
							position: absolute;
							top: -2rpx;
							right: -8rpx;
							width: 46%;
							height: 112%;
							opacity: 1;
							cursor: pointer;
							transition: opacity 0.2s;

							&:hover {
								opacity: 0.8;
							}
						}

						.sendMsg.disabled {
							opacity: 0.5;
							pointer-events: none;
						}

						.countdown-mask {
							position: absolute;
							right: 20rpx;
							top: 10rpx;
							background: rgba(0, 0, 0, 0.4);
							color: #fff;
							padding: 6rpx 16rpx;
							border-radius: 8rpx;
							font-size: 28rpx;
						}

						.input-field {
							width: 100%;
							border: none;
							height: 100%;
							font-size: 42rpx;
							background: transparent;
							outline: none;
						}
					}
				}

				.forgot-password {
					text-align: right;
					margin-bottom: 40rpx;
					margin-top: 20rpx;

					.forgot-link {
						color: #4CAF50;
						font-size: 56rpx;
						text-decoration: underline;
						cursor: pointer;
						transition: opacity 0.2s;

						&:hover {
							opacity: 0.7;
						}
					}
				}

				.button-group {
					display: flex;
					justify-content: center;
					align-items: center;
					margin-top: 100rpx;

					image {
						margin-left: 50rpx;
						cursor: pointer;
						transition: opacity 0.2s;

						&:hover {
							opacity: 0.8;
						}
					}
				}

				.switch-tabs {
					margin-top: 40rpx;
					display: flex;
					justify-content: center;

					.tab {
						margin: 0 20rpx;
						font-size: 32rpx;
						color: #666;
						cursor: pointer;
						transition: all 0.2s;

						&.active {
							color: #333;
							font-weight: 600;
							text-decoration: underline;
						}

						&:hover {
							color: #333;
						}
					}
				}
			}
		}
	}

	@keyframes modalSlideIn {
		from {
			transform: translateY(-50rpx);
			opacity: 0;
		}

		to {
			transform: translateY(0);
			opacity: 1;
		}
	}
</style>